import { loginAPI, getAuthor, autoLogin,agentLogin, thirdlogin } from "@/api/user";
import { getToken, removeToken, getCookie, setToken,setCookie } from "@/utils/auth";

//use for logout
import { resetRouter } from "@/router";
import router from "@/router";
import { Message } from "element-ui";

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    roleType:'',
    roleName:'',
    userid:'',  //登录用户id
    childRoleName:'',
    authGroupIds: JSON.parse(getCookie("authGroupIds") || "[]")
  };
};

const state = getDefaultState();

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_USERID: (state, userid) => {
    state.userid = userid
  },
  SET_ROLENAME: (state, roleName) => {
    state.roleName = roleName
  },
  SET_CHILDROLENAME: (state, childRoleName) => {
    state.childRoleName = childRoleName
  },
  RESET_STATE: state => {
    Object.assign(state, getDefaultState());
  },
  SET_ROLETYPE: (state, roleType) => {
    state.roleType = roleType;
  },
  SET_AUTH_GROUPIDS: (state, authGroupIds) => {
    state.authGroupIds = authGroupIds;
  }
};

const actions = {
  // 账密登录
  login({ commit }, userInfo) {
    const { logid, password, userType } = userInfo;
    return new Promise((resolve, reject) => {
      loginAPI({ logid: logid.trim(), password: password, userType:userType })
        .then(response => {
          resolve(response);
        })
        .catch(error => {
          reject(error);
        });
    });
  },

  // 用户授权请求
  getAuthor({ commit }, data) {
    return new Promise((resolve, reject) => {
      getAuthor({
        ReturnUrl:
          window.location.origin +
          "/index.html" +
          "?systemtype=0&oauthlt=1&ReturnType=1"
      })
        .then(response => {
          window.location.href = response.entity;
          resolve(response);
        })
        .catch(error => {
          reject(error);
        });
    });
  },

   // 单点登录：运营平台token登录
  autoLogin({ commit }, data) {
    return new Promise((resolve, reject) => {
      let LoginData = {
        token: data.token,
        ReturnUrl:
          window.location.origin +
          "/index.html" +
          "?systemtype=0&oauthlt=1&ReturnType=1",
        type: 1
      };
      autoLogin(LoginData)
        .then(response => {
          if(response.code === 0){
            const { data } = response;
            commit("SET_NAME", data.username);
            commit("SET_ROLETYPE", data.suitrole);
            commit("SET_USERID", data.userid);
            commit('SET_TOKEN', data.accesstoken);
            setToken(data.accesstoken);
            setCookie("refreshtoken", data.refreshtoken);
            setCookie("UserName", data.username);
            setCookie("userid", data.userid);
            setCookie("roleType", data.suitrole);
            resolve();
          }else{
            resolve(response);
          }
        })
        .catch(error => {
          reject(error);
        });
    });
  },
   // 单点登录：测试专用
   agentLogin({ commit }, data) {
    return new Promise((resolve, reject) => {
      let LoginData = {
        token: data.token,
        ReturnUrl:
          window.location.origin +
          "/index.html" +
          "?systemtype=0&oauthlt=1&ReturnType=1",
        type: 1
      };
      agentLogin(LoginData)
        .then(response => {
          const { data } = response;
          commit("SET_NAME", data.username);
          commit("SET_ROLETYPE", data.suitrole);
          commit("SET_USERID", data.userid);
          commit('SET_TOKEN', data.accesstoken);
          setToken(data.accesstoken);
          setCookie("refreshtoken", data.refreshtoken);
          setCookie("UserName", data.username);
          setCookie("userid", data.userid);
          setCookie("roleType", data.suitrole);
          resolve();
        })
        .catch(error => {
          reject(error);
        });
    });
  },
  // 刷新token 以旧换新
  thirdlogin({ commit }, data) {
    return new Promise((resolve, reject) => {
      thirdlogin(data)
        .then(response => {
          const { entity } = response;
          commit("SET_NAME", entity.usrName);
          commit("SET_ROLETYPE", entity.role);
          commit("SET_AUTH_GROUPIDS", entity.authGroupIds);
          resolve();
        })
        .catch(error => {
          reject(error);
        });
    });
  },

  // remove token,use for logout
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken(); // must remove  token  first
      commit("RESET_STATE");
      resolve();
      resetRouter();
    });
  },
  checkToken({ commit, state }) {
    if (state.token != "undefined" && state.token != undefined) {
      router.push("/");
    }
  }

};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
